package com.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: sn
 * @Desc something
 * @Date: 2022/4/27
 */
public class TestReentrantLock {
    static List<Thread> list = new ArrayList<>();
    //代码都没有变，只是把synchronized关键字变成了ReentrantLock
    static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(() -> {
                lock.lock();
                //log.debug("thread executed");
                System.out.println(String.format("{%s}-thread executed",Thread.currentThread().getName()));
                try {
                    TimeUnit.MILLISECONDS.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.unlock();
            }, "t" + i);
            list.add(t);
        }
        //log.debug("---启动顺序 调度顺序或者说获取锁的顺序讲道理是正序0--9----");
        System.out.println("---启动顺序 调度顺序或者说获取锁的顺序讲道理是正序0--9----");
        lock.lock();
        for (Thread thread : list) {
            //log.debug("{}-启动顺序--正序0-9", thread.getName());
            System.out.println(String.format("{%s}-启动顺序--正序0-9", thread.getName()));
            thread.start();//  CPU 调度？
            TimeUnit.MILLISECONDS.sleep(1);
        }

        //log.debug("-------执行顺序--正序9-0");
        System.out.println("-------执行顺序--正序9-0");
        lock.unlock();
    }

}
